package com.lagou.controller;

import com.lagou.dao.StudentDaoImpl;
import com.lagou.entity.Student;
import com.lagou.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Student student = new Student(username, password);
        StudentService studentService = new StudentService(new StudentDaoImpl());
        Student s1 = studentService.login(student);
        if(s1 != null){
            System.out.println("登陆成功");
            Cookie cookie = new Cookie("name","zhangfei");
            cookie.setMaxAge(60*60);//设置cookie过期时间
            request.getSession().setAttribute("username",student.getUsername());
            request.getRequestDispatcher("/list.jsp").forward(request,response);
        }else{
            System.out.println("账号密码错误!");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
